package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author liam
 * @description
 * @date 2020/3/4-21:55
 * @Version 1.0.0
 */
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //1.根据用户名查询用户
        User user = userDao.findByUsername(username);
        if (user == null) {
            //没有该用户名则直接返回
            return null;
        }

        //2.根据用户id查询出他所有的角色
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        //3、循环角色集合查询角色对应的权限集合（得到的权限集合需要set给Role对象里面的permissions属性）
        if(CollectionUtil.isNotEmpty(roles)){
            for (Role role : roles) {
                Set<Permission> permissions = permissionDao.findPermissionsByRoleId(role.getId());
                role.setPermissions(permissions);
            }
        }
        user.setRoles(roles);
        return user;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.先调用分页插件，告知mybatis开始分页查询
        Page<Object> page = PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //2.调用userdao，进行查询
        List<User> users = userDao.findByCondition(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), users);
    }

    @Override
    public void add(User user) {
        //1.插入用户并返回其ID
        userDao.insert(user);
        //2.维护user_role关系表
        Integer userId = user.getId();
        List<Integer> roleIds = user.getRoleIds();
        if (CollectionUtil.isNotEmpty(roleIds)) {
            userDao.setUserIdAndRoleIdsBatch(userId,roleIds);
        }
    }

    @Override
    public Map<String, Object> findById4Edit(Integer id) {
        //1.查询用户及其角色id
        User user = userDao.selectByPrimaryKey(id);
        List<Integer> roleIds = userDao.findRoleIdsByUserId(id);

        //2.查询所有角色
        List<Role> roles = roleDao.findAll();
        //3.构建map返回
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roleIds", roleIds);
        map.put("roles", roles);
        return map;
    }

    @Override
    public void edit(User user) {
        Integer userId = user.getId();
        List<Integer> roleIds = user.getRoleIds();
        //1.更新用户并删除原有的user_role关系
        userDao.updateByPrimaryKeySelective(user);
        userDao.deleteAssociationByUserId(userId);
        //2.新建user_role关系
        if (CollectionUtil.isNotEmpty(roleIds)) {
            userDao.setUserIdAndRoleIdsBatch(userId,roleIds);
        }
    }

    @Override
    public void delete(Integer id) {
        //先删除user_role关系，再删除user
        userDao.deleteAssociationByUserId(id);
        userDao.deleteByPrimaryKey(id);
    }

}
